package com.example.weathermvvm.data.db

import android.content.SharedPreferences
import android.util.Log
import androidx.preference.PreferenceManager
import com.example.weathermvvm.MyOwnApplication
import com.example.weathermvvm.data.model.weather.Weather
import com.google.gson.Gson

/**
 *
 * @Author： LJH
 * @Time： 2022/8/15
 * @description：天气数据的缓存Dao
 */
class WeatherDao {

    /**
     * 缓存天气信息，以Json格式
     * @param weather Weather?
     */
    fun cacheWeatherInfo(weather: Weather?){
        if (weather == null) return
        PreferenceManager.getDefaultSharedPreferences(MyOwnApplication.context).edit {
            val weatherJson = Gson().toJson(weather)
            putString("weather",weatherJson)
        }
    }

    /**
     * 获取缓存天气信息，Json转换成Weather Bean
     * @return Weather?
     */
    fun getCachedWeatherInfo():Weather?{
        Log.d("WeatherDao","getCachedWeatherInfo()获取缓存天气信息...")
        val weatherInfo = PreferenceManager.getDefaultSharedPreferences(MyOwnApplication.context).getString("weather",null)
        weatherInfo?.let {
            return Gson().fromJson(it,Weather::class.java)
        }
        return null
    }

    /**
     * 缓存背景图片路径
     * @param bingPic String?
     */
    fun cacheBingPic(bingPic: String?){
        if (bingPic == null) return
        PreferenceManager.getDefaultSharedPreferences(MyOwnApplication.context).edit {
            putString("bing_pic",bingPic)
        }
    }

    /**
     * 获取缓存的背景图片路径
     * @return String?
     */
    fun getCachedBingPic():String? = PreferenceManager.getDefaultSharedPreferences(MyOwnApplication.context).getString("bing_pic",null)

    /**
     * SharedPreferences扩展函数
     * @receiver SharedPreferences
     * @param action [@kotlin.ExtensionFunctionType] Function1<Editor, Unit>
     */
    private fun SharedPreferences.edit(action:SharedPreferences.Editor.() -> Unit){
        val editor = edit()
        action(editor)
        editor.apply()
    }
}